package com.project.schoolFoodShare.controller.index;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.schoolFoodShare.domain.FoodList;
import com.project.schoolFoodShare.domain.FoodType;
import com.project.schoolFoodShare.domain.Result;
import com.project.schoolFoodShare.domain.User;
import com.project.schoolFoodShare.service.FoodListService;
import com.project.schoolFoodShare.service.FoodTypeService;
import com.project.schoolFoodShare.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@ResponseBody
@RequestMapping("index")
public class IndexController {

    @Autowired
    private FoodListService foodListService;
    @Autowired
    private FoodTypeService foodTypeService;
    @Autowired
    private UserService userService;

    @GetMapping("indexManage")
    public Result indexManage() {
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUserType,1);
        int userNum = userService.count(wrapper);
        jsonObject.put("userNum",userNum);

        int foodNum = foodListService.count();
        jsonObject.put("foodNum",foodNum);

        //分享评论数
        QueryWrapper<FoodList> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().last("limit 20");
        List<FoodList> foodLists = foodListService.list(queryWrapper);
        List<String> nameList = new ArrayList<>();
        List<Integer> commentList = new ArrayList<>();
        for (FoodList foodList : foodLists) {
            nameList.add(foodList.getName());
            commentList.add(foodList.getComment());
        }
        jsonObject.put("nameList",nameList);
        jsonObject.put("commentList",commentList);

        //获取分类分享.
        List<JSONObject> typeList = new ArrayList<>();
        List<FoodType> list = foodTypeService.list();
        for (FoodType foodType : list) {
            QueryWrapper<FoodList> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(FoodList::getTypeId,foodType.getId());
            int count = foodListService.count(queryWrapper1);
            JSONObject object = new JSONObject();
            object.put("name",foodType.getName());
            object.put("value",count);
            typeList.add(object);
        }
        jsonObject.put("typeList",typeList);

        return Result.success(jsonObject);
    }

}
